﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.Threading;
using System.Diagnostics;
using System.IO;
using Microsoft.Win32;

namespace AutoUpdate
{
	public partial class Form1 : Form
	{
		 
		public Form1()
		{
			InitializeComponent();
			
		}
		private AutoUpdateConfig config = Program.config;
		private void Form1_Load(object sender, EventArgs e)
		{
			ZipHelper.UnZip(config.Files[0].Substring(config.Files[0].LastIndexOf("/") + 1), @"ccc");
			return;

			#region 调用系统的解压工具
			////使用OpenSubKey()打开项，获得RegistryKey对象，当路径不存在时，为Null。第二个参数为true，表示可写，可读，可删；省略时只能读。
			//RegistryKey hklm = Registry.ClassesRoot;
			//RegistryKey hkSoftWare = hklm.OpenSubKey(@".zip");
			//var a=hkSoftWare.GetValue("").ToString();
			//var haoya = hklm.OpenSubKey(a+@"\shell\open\command");

			//var cmd = haoya.GetValue("");

			//hklm.Close();
			//hkSoftWare.Close();
			#endregion
			CheckVersion(config.Url);

			
		}

		private void Wc_DownloadFileCompleted(object sender, AsyncCompletedEventArgs e)
		{
			 

			//MessageBox.Show("下载完成");
			ZipHelper.UnZip(config.Files[0].Substring(config.Files[0].LastIndexOf("/") + 1), @"..\");
			Thread.Sleep(1010);

			var p= Path.GetFullPath(".."); 
			Process.Start(p+@"\" +config.MainExe);
			Thread.Sleep(1010);
			Application.Exit();

		}

		public   void CheckVersion(string url)
		{
			using (var wc = new WebClient())
			{
				wc.DownloadStringCompleted += Wc_DownloadStringCompleted;
				wc.DownloadStringAsync(new Uri(Program.config.Url));

			}

		}

		private   void Wc_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
		{
			AutoUpdateConfig serverConfig = null;
			var configJson = e.Result;
			if (!string.IsNullOrEmpty(configJson))
				serverConfig = Newtonsoft.Json.JsonConvert.DeserializeObject<AutoUpdateConfig>(configJson);
			if (serverConfig == null) return;
			if (serverConfig.Version != Program.config.Version)
			{
				ConfigExt.SaveConfig(serverConfig);
				using (var wc = new WebClient())
				{
					wc.DownloadFileAsync(new Uri(config.Files[0]), config.Files[0].Substring(config.Files[0].LastIndexOf("/") + 1));
					wc.DownloadFileCompleted += Wc_DownloadFileCompleted;
				}

			}
		}

		private void linkLabel1_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
		{
			Application.Exit();
			 
		}
	}
}
